/**
 * Called to process data submitted to the spreadsheet from a form.
 */
function onSubmit(e) {
  // Dump to log if in testing org
  if(e.namedValues['Organisation type'][0] == ORG_TYPE_TEST) {
    for(nv in e.namedValues) {
      Logger.log(nv + " : " + e.namedValues[nv]);
    }
  }
  
  // Parse form data
  var booking = parseRequestToObj_(e);
  
  if(booking != null) {
    Logger.log("Processing booking from %s", booking.organisation.name);
    processBooking(booking);
  }
}

/**
 * Parses a string for a given value and returns if the value is contained in the string.
 */
function parseBoolInValue_(inStr, value) {
  if(inStr == null) {
    return false;
  }
  return inStr.indexOf(value) >= 0;
}

/**
 * Converts form date strings into GS dates.
 */
function parseDate_(dateStr) {
  var d = new Date(0);
  var dParts = dateStr.split("/");
  
  Logger.log(dateStr);
  var yr = Number(dParts[2]);
  var mo = Number(dParts[1] - 1); // setMonth is 0-based
  var da = Number(dParts[0]);
  Logger.log(yr + " | " + mo + " | " + da);
  
  // Date elements
  d.setFullYear(yr);
  d.setMonth(mo);
  d.setDate(da);
  
  Logger.log(d);
  
  // Time elements
  d.setHours(0);
  d.setMinutes(0);
  d.setSeconds(0);
  d.setMilliseconds(0);
  
  return d;
}

/**
 * Calculates the timeslot requested.
 */
function parseTimeslot_(timeStr) {
  if(timeStr == null) {
    return null;
  }
  if(timeStr.indexOf("Morning") >= 0) {
    if(timeStr.indexOf("Afternoon") >= 0) {
      return EVENT_TIME_DAYTIME;
    }
    if(timeStr.indexOf("Evening") >= 0) {
      return EVENT_TIME_ALLDAY;
    }
    return EVENT_TIME_MORNING;
  }
  if(timeStr.indexOf("Afternoon") >= 0) {
    if(timeStr.indexOf("Evening") >= 0) {
      return EVENT_TIME_LATEDAY;
    }
    return EVENT_TIME_AFTERNOON;
  }
  if(timeStr.indexOf("Evening") >= 0) {
    return EVENT_TIME_EVENING;
  }
  return null;
}

/**
 * Parses a value from an array.
 */
function parseValue_(inArr) {
  for(i = 0; i < inArr.length; i ++) {
    if(inArr[i] != null && inArr[i].length > 0) {
      return inArr[i];
    }
  }
  return null;
}

/**
 * Parses the form response.
 */
function parseRequestToObj_(e) {
  
  // Read values from request
  var strOrgName = e.namedValues['Organisation name'][0];
  var strOrgType = e.namedValues['Organisation type'][0];
  
  var strContactName = e.namedValues['Contact name'][0];
  var strContactTelephone = e.namedValues['Contact telephone number'][0];
  var strContactEmail = e.namedValues['Contact e-mail address'][0];
  
  var strHouseBooking = e.namedValues['House booking'][0];
  var strFieldBooking = e.namedValues['Field booking'][0];
  
  var strEventType = parseValue_(e.namedValues['Event type']);
  
  var strArrivalDate = parseValue_(e.namedValues['Arrival date']);
  var strDepartureDate = parseValue_(e.namedValues['Departure date']);
  var strEventTime = parseValue_(e.namedValues['Event time']);
  
  var strParticipants = e.namedValues['Participants'][0];
  var strLeaders = e.namedValues['Leaders'][0];
  
  var strEquipmentHire = e.namedValues['Equipment hire'][0];
  var strTents = e.namedValues['Tent hire'][0];
  
  var strNotes = e.namedValues['Special requirements'][0];
  
  // Calculate additional values
  var strEventName = strOrgName + "_" + strArrivalDate;
  var blDayBooking = parseBoolInValue_(strHouseBooking, "one-day") || parseBoolInValue_(strFieldBooking, "one-day");
  var blHouseBooking = parseBoolInValue_(strHouseBooking, "Yes");
  var blFieldBooking = parseBoolInValue_(strFieldBooking, "Yes");
  var strEventType2 = (strEventType == null ? (blHouseBooking ? (blDayBooking ? strEventType : EVENT_TYPE_HOUSE_OVERNIGHT) : blFieldBooking ? (blDayBooking ? EVENT_TYPE_FIELD_DAY : EVENT_TYPE_FIELD_OVERNIGHT) : null) : strEventType);
  
  var obj = {
      "timestamp"       : new Date()
    , "eventName"       : strEventName
    , "organisation"    : {
          "name" : strOrgName
        , "type" : strOrgType
      }
    , "contact"         : {
          "name"      : strContactName
        , "telephone" : strContactTelephone
        , "email"     : strContactEmail
      }
    , "eventType"       : strEventType2
    , "eventTime"       : parseTimeslot_(strEventTime)
    , "isHouseBooking"  : blHouseBooking
    , "isFieldBooking"  : blFieldBooking
    , "arrivalDate"     : parseDate_(strArrivalDate)
    , "departureDate"   : parseDate_(blDayBooking ? strArrivalDate : strDepartureDate)
    , "equipment"       : {
          "fullyEquipped" : parseBoolInValue_(strEquipmentHire, "Fully equipped")
        , "tents"         : strTents
      }
    , "participants"    : Number(strParticipants)
    , "leaders"         : Number(strLeaders)
    , "notes"           : strNotes
    , "status"          : "NEW"
    , "docs"            : {}
  };
  Logger.log(obj);
  
  return obj;
}
